# -*- coding: utf-8 -*-

__author__	= 'souheil@pilotsystems.net'
__docformat__	= 'plaintext'


from AccessControl import ClassSecurityInfo
from Globals       import InitializeClass
from Acquisition   import aq_base, aq_parent, aq_inner
from Products.CMFCore.permissions import ModifyPortalContent
from Products.CMFCore.utils import getToolByName
from Products.ATContentTypes.content.folder import ATFolder
from Products.PloneGossip.config import REVIEWABLE_TYPES
from Products.PloneGossip import security
from Products.CMFPlone.interfaces.NonStructuralFolder import INonStructuralFolder


class PGContainer( ATFolder ):
    """
    Base forum container
    """
    allowed_content_types       = None
    allow_discussion            = False
    _at_rename_after_creation   = True

    # Interfaces
    __implements__ = ATFolder.__implements__

    # Security
    security = ClassSecurityInfo()


    security.declarePrivate('getGossipCatalog')
    def getGossipCatalog(self):
        """
        Returns the dedicated catalog
        It can be easily switched to portal_catalog
        """
        return self.portal_catalog


    security.declarePrivate('gossipQuery')
    def gossipQuery(self,
                    limit=1,
                    path=None,
                    portal_type=None,
                    review_state=None,
                    sort_order='reverse',
                    search_term=None):
        """
        Returns the list of container's $limit last children
        """
        cat   = self.getGossipCatalog()
        query = {
            'path': path or '/'.join(self.getPhysicalPath()),
            'limit': limit,
            'portal_type': portal_type or self.allowed_content_types,
            'sort_order': sort_order,
            'sort_on': 'created',
            }

        if review_state:
            query['review_state'] = review_state

        if search_term:
            query['SearchableText'] = search_term,
        
        return cat(query)


    security.declareProtected('View', 'getAllContents')
    def getAllContents(self, limit=None, search_term=None):
        """
        Returns the list of all children
        """
        return self.gossipQuery(limit=limit, search_term=search_term)


    security.declareProtected('View', 'getDirectContents')
    def getDirectContents(self, limit=None, sort_order=None):
        """
        Returns the list of the first level children
        """
        path = {
            'depth': 1,
            'query': '/'.join(self.getPhysicalPath())
            }
        
        return self.gossipQuery(limit=limit, path=path, sort_order=sort_order)
    

    security.declareProtected('View', 'getReviewableContents')
    def getReviewableContents(self, limit=5):
        """
        Returns the contents to review
        """
        return self.gossipQuery(limit=limit,
                                portal_type=REVIEWABLE_TYPES,
                                review_state='pending')


    security.declareProtected('View', 'getNumberOfChildren')
    def getNumberOfChildren(self):
        """
        Returns the number of children of the container
        """
        return len(self.getDirectContents())

    
    security.declareProtected('View', 'getTotalNumberOfChildren')
    def getTotalNumberOfChildren(self):
        """
        Returns the number of children of the container
        """
        return len(self.getAllContents())
    

    security.declareProtected('View', 'getMyParent')
    def getMyParent(self):
        """
        """
        return aq_parent(aq_inner(self))


    security.declarePublic('canSetDefaultPage')
    def canSetDefaultPage(self):
        """
        No Default Page can be set for this folderish type
        """
        return False
    

    security.declareProtected('View', 'getCreationDate')
    def getCreationDate(self, long_format=True):
        """
        Return a Plone standardly formated date
        """
        return self.toLocalizedTime(self.creation_date,
                                    long_format=long_format)


    security.declareProtected('View', 'getReviewState')
    def getReviewState(self):
        """
        """
        wtool = self.portal_workflow
        state = wtool.getInfoFor(self, 'review_state')
        return state or None


    security.declareProtected('View', 'getAuthor')
    def getAuthor(self):
        """
        get the author of the item
        """
        mtool = self.portal_membership
        member = mtool.getMemberInfo(self.Creator())
        if member is not None:
            member['portrait'] = mtool.getPersonalPortrait(self.Creator())
            return member
        return None


    security.declarePrivate('getPermission')
    def getPermission(self,
                      perm_type=None,
                      right=None,
                      anon=True,
                      meta_type=None):
        """
        fetch the permission in the security module of
        PloneGossip
        """
        mtool = self.portal_membership

        # We do not allow anonymous user to get this
        if not anon and mtool.isAnonymousUser():
            return False

        # We fetch the right in 'security'
        if not right and perm_type:
            right = getattr(security, '%s%s' % (perm_type, meta_type or self.meta_type))
            
        return right and mtool.checkPermission(right, self)


    security.declareProtected('View', 'isReviewable')
    def isReviewable(self):
        """
        Return true if the item is reviewable in the context
        by the current user
        """
        if self.getReviewState() == 'pending':
            return self.getPermission(perm_type='Validate')
        return False


    security.declareProtected('View', 'isThreadAddable')
    def isThreadAddable(self):
        """
        Return true if a thread is addable in the context
        by the current user
        """
        return self.getPermission(perm_type='Add', meta_type='PGThread')


    security.declareProtected('View', 'isPostAddable')
    def isPostAddable(self):
        """
        Return true if a post is addable in the context
        by the current user
        """
        return self.getPermission(perm_type='Add', meta_type='PGPost')
    
        
    security.declareProtected('View', 'isQuotable')
    def isQuotable(self):
        """
        Return true if the item is addable in the context
        by the current user
        """
        return self.getPermission(perm_type='Add', meta_type='PGPost', anon=False) 


    security.declareProtected('View', 'isDeletable')
    def isDeletable(self):
        """
        Checks the delete objects right
        """
        return self.getPermission(right='Delete objects')


    security.declareProtected('View', 'getNotAddableTypes')
    def getNotAddableTypes(self):
        """
        Hide 'add to folder' dropdown menu
        """
        ignored  = self.allowed_content_types
        return ignored


InitializeClass(PGContainer)
